<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/14
 * Time: 17:48
 */

namespace app\teacher\controller;


use app\admin\model\ApiResponse;
use app\common\utils\OssUtil;
use app\teacher\lib\TeacherBaseController;
use library\aliYunOss;
use think\Log;
use think\Request;

class Files extends TeacherBaseController
{

    /**
     * gmt_iso8601
     * 生成ISO8601标准格式的时间
     *
     * @param $time
     * @return string
     */
    private function gmt_iso8601($time) {
        $dtStr = date("c", $time); //格式为2016-12-27T09:10:11+08:00
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601); //格式为2016-12-27T09:12:32+0800
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);//格式为2016-12-27T09:12:32
        return $expiration."Z";
    }

    public function oss_policy(string $type, int $maxsize = 500*1024*1024) {

        if (!in_array($type, ['image','video','audio',])) {
            return json(array('code'=>1010, 'msg'=>'类型不正确', 'data'=>null));
        }
        $dir = $type; // 上传目录

        $bucket = config('aliYunOSS.Bucket');
        // 计算过期时间
        $end = time() + 30;
        // 生成ISO8601格式时间
        $expiration = $this->gmt_iso8601($end);

        $conditions = [];
        $conditions[] = [0=>'content-length-range', 1=>0, 2=>$maxsize]; // 最大文件大小.用户可以自己设置 100M

        $start = [0=>'starts-with', 1=>'$key', 2=>$dir]; //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $conditions[] = $start;

        $arr = ['expiration'=>$expiration,'conditions'=>$conditions];
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, config('aliYunOSS.AccessKeySecret'), true));

        $response = [];
        $response['accessid'] = config('aliYunOSS.AccessKeyId');
        $response['host'] = 'http://'.$bucket.'.'.config('aliYunOSS.EndPoint');
        $response['bucket'] = $bucket;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['dir'] = $dir;  //这个参数是设置用户上传指定的前缀
        $response['dns'] = OssUtil::DNS_HOST;

        return ApiResponse::success($response);
    }

    /**
     * CKEditor 上传接口
     * @param Request $request
     * @return array
     */
    public function upload_ckeditor(Request $request) {
        $file = $request->file('upload');
        if (!$file->checkImg()) {
            return [
                'uploaded' => false,
                'error' => ['message' => '只能上传图片']
            ];
        }
        if (!$file->checkSize(512*1024)) {
            return [
                'uploaded' => false,
                'error' => ['message' => '大小不能超过512K']
            ];
        }

        $name = sha1(microtime(true).mt_rand(1000,9999)) . '.jpg';
        $path = 'editor/' . $name;
        $tmp = $file->getInfo('tmp_name');
        try{
            $re = OssUtil::put($path, $tmp);
            return [
                'url' => $re,
                'uploaded' => true
            ];
        }catch (\Exception $e){
            Log::error($e->getMessage());
            return ['uploaded' => false, 'error' => ['message' => $e->getMessage()]];
        }
    }



    protected static $baseDir = ROOT_PATH.'public'.DS.'uploads'; // 保存目录
    protected static $urlPath = '/public/uploads'; // url路径

    // 新文件名
    protected static function newName()
    {
        return time().rand(100000, 999999);
    }
    /**
     * imgSync
     * 自动下载内容中的远程图片并同步到阿里云OSS
     *
     * @author zhengkai
     * @date 2018-05-07
     *
     * @param $body
     * @return mixed|string
     */
    public static function imgSync($body)
    {
        $content = stripcslashes($body);
        $imgArr = [];
        $pattern = "/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $content,$imgArr);
        $imgArr = array_unique($imgArr[1]);

        // 文件保存目录
        $savePath = self::$baseDir.'/remote';
        Log::log($savePath);
        // 目录不存在就自动创建
        if (!is_dir($savePath)) mkdir($savePath, 0775, true);

        set_time_limit(0);
        foreach ($imgArr as $key=>&$val) {
            $strUrl = parse_url($val);
            if ($strUrl['host']==='image.cloud.51taojingu.com') break;

            $val = trim($val);
            $getImg = @file_get_contents($val);
            $imgName = self::newName().'.'.substr($val, -3, 3);
            $path = $savePath.'/'.$imgName;
            $url = self::$urlPath.'/remote/'.$imgName;

            if ($getImg) {
                $fp = @fopen ( $path, "w" );
                @fwrite ( $fp, $getImg );
                @fclose ( $fp );

                $syncAli = aliYunOss::getInstance()->uploadFile($imgName, $path, 'image/');

                $imgUrl = $val;
                if ($syncAli) {
                    $imgUrl = str_replace('tjg-customer-flow-division.oss-cn-shanghai.aliyuncs.com', 'image.cloud.51taojingu.com', $syncAli['info']['url']);

                    // 删除本地原图
                    @unlink($path);
                }
            }
            // 替换原来的图片地址
            $content = str_replace($val, $imgUrl, $content);
        }
        return $content;
    }
}